package cn.kicsy.www.anonymous_bbs.service;

import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class SensitiveWordFilterService {
    
    // 敏感词集合
    private final Set<String> sensitiveWords = new HashSet<>();
    
    // 构造函数，初始化敏感词库
    public SensitiveWordFilterService() {
        // 这里添加一些示例敏感词
        addSensitiveWord("敏感词1");
        addSensitiveWord("敏感词2");
        addSensitiveWord("敏感词3");
        addSensitiveWord("非法");
        addSensitiveWord("违法");
        addSensitiveWord("色情");
        addSensitiveWord("暴力");
        addSensitiveWord("赌博");
        addSensitiveWord("毒品");
        // 可以根据需要添加更多敏感词
    }
    
    /**
     * 添加敏感词
     * @param word 要添加的敏感词
     */
    public void addSensitiveWord(String word) {
        sensitiveWords.add(word.toLowerCase());
    }
    
    /**
     * 移除敏感词
     * @param word 要移除的敏感词
     */
    public void removeSensitiveWord(String word) {
        sensitiveWords.remove(word.toLowerCase());
    }
    
    /**
     * 检查文本中是否包含敏感词
     * @param text 要检查的文本
     * @return 是否包含敏感词
     */
    public boolean containsSensitiveWords(String text) {
        if (text == null || text.isEmpty()) {
            return false;
        }
        
        String lowerText = text.toLowerCase();
        for (String word : sensitiveWords) {
            if (lowerText.contains(word)) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 过滤敏感词，用*替换敏感词
     * @param text 要过滤的文本
     * @return 过滤后的文本
     */
    public String filterSensitiveWords(String text) {
        if (text == null || text.isEmpty()) {
            return text;
        }
        
        String result = text;
        String lowerText = text.toLowerCase();
        
        for (String word : sensitiveWords) {
            if (lowerText.contains(word)) {
                // 创建与敏感词长度相同的*字符串
                String replacement = new String(new char[word.length()]).replace('\0', '*');
                
                // 构建正则表达式，忽略大小写
                Pattern pattern = Pattern.compile(Pattern.quote(word), Pattern.CASE_INSENSITIVE);
                Matcher matcher = pattern.matcher(result);
                result = matcher.replaceAll(replacement);
            }
        }
        
        return result;
    }
}